import React, { memo, useEffect, useState } from 'react'
import { useUserToken, useScrollPosition, useLocalStorage } from "./hooks"
import './style.css'

function useLogLife(cName) {
  useEffect(() => {
    console.log(`${cName}组件挂载了`)
    return () => {
      console.log(`${cName}组件卸载了`)
    }
  }, [cName])
}

const Home = memo(() => {
  useLogLife('Home')
  return (
    <div>Home</div>
  )
})

const About = memo(() => {
  useLogLife('About')
  return (
    <div>About</div>
  )
})

const MyContext = memo(() => {
  const [user, token] = useUserToken()
  
  return (
    <div>MyContext: {user.name}-{token}</div>
  )
})

const WindowScorllPostion = memo(() => {
  const [scrollX, scrollY] = useScrollPosition()

  return (
    <div>WindowScorllPostion: {scrollX} - {scrollY}</div>
  )
})

const GetLocalStorage = memo(() => {
  const [token, setToken] = useLocalStorage('token')
  function setTokenHandle() {
    setToken('newToken')
  }

  const [avatarUrl, setAvatarUrl] = useLocalStorage("avatarUrl")
  function setAvatarUrlHandle() {
    setAvatarUrl("https//www.baidu.com/avatar.png")
  }

  return (
    <div>
      <h4>GetLocalStorage: {token}</h4>
      <button onClick={setTokenHandle}>设置token</button>
      <h4>avatarURL: {avatarUrl}</h4>
      <button onClick={setAvatarUrlHandle}>设置新头像地址</button>  
    </div>
  )
})

const App = memo(() => {
  const [isShow, setIsShow] = useState(true)
  
  return (
    <div className='app'>
      <h3>01_打印生命周期</h3>
      <button onClick={e => setIsShow(!isShow)}>切换</button>
      { isShow && <Home/> }
      { isShow && <About/> }

      <h3>02_Context获取数据</h3>
      <MyContext/>

      <h3>03_获取窗口滚动位置</h3>
      <WindowScorllPostion/>

      <h3>04_useLocalStorage Hook</h3>
      <GetLocalStorage/>
    </div>
  )
})

export default App